package com.yf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.domain.TsUser;
import com.yf.redis.DistributedRedisLock;
import com.yf.redis.RedisKey;
import com.yf.service.TsRoleService;
import com.yf.service.TsUserService;
import com.yf.mapper.TsUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
* @author yangfeng
* @description 针对表【ts_user】的数据库操作Service实现
* @createDate 2024-03-28 14:49:28
*/
@Service
@Slf4j
public class TsUserServiceImpl extends ServiceImpl<TsUserMapper, TsUser>
    implements TsUserService{
    @Resource
    private TsRoleService tsRoleService;
    @Resource
    private UserServiceAnother userServiceAnother;
    @Resource
    private DistributedRedisLock distributedRedisLock;


    @Transactional
    @Override
    public boolean addUser(String name) {
        try {
            TsUser u = new TsUser();
            u.setName(name);
            boolean b = save(u);
//        throw new RuntimeException();
//            String s = null;
//            System.out.println(s.length());
            tsRoleService.addRole(name);
            return b;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public boolean addUser1(String name) {
        log.info("当前线程 threadName = {}",Thread.currentThread().getName());
        Boolean lock = distributedRedisLock.lock(RedisKey.USER_ADD_LOCK + name,1,1, TimeUnit.SECONDS);
        try {
            if(lock){
                TsUser user = new TsUser();
                user.setName(name);
                userServiceAnother.saveUser(user);
                return true;
            }else{
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //获取锁成功并且是自己加的锁则释放
            distributedRedisLock.unlock(RedisKey.USER_ADD_LOCK + name);
        }


    }
    @Transactional
    @Override
    public void saveUser(TsUser user) {
        this.save(user);
        throw new RuntimeException("数据保存完出现异常");
    }
}




